<template>
  <div class="book-management">
    <el-button type="primary" @click="dialogVisible = true">添加图书</el-button>
    <el-table :data="books" style="width: 100%">
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="title" label="书名" width="180"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="copies" label="库存"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="deleteBook(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加图书" :visible.sync="dialogVisible" width="30%">
      <el-form :model="newBook" label-width="80px">
        <el-form-item label="书名">
          <el-input v-model="newBook.title"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="newBook.author"></el-input>
        </el-form-item>
        <el-form-item label="库存">
          <el-input-number v-model="newBook.copies" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addBook">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      newBook: {
        id: null,
        title: '',
        author: '',
        copies: 0
      }
    }
  },
  computed: {
    books() {
      return this.$store.state.books
    }
  },
  methods: {
    addBook() {
      this.$store.commit('addBook', this.newBook)
      this.dialogVisible = false
      this.newBook = { id: null, title: '', author: '', copies: 0 }
    },
    deleteBook(id) {
      this.$store.commit('deleteBook', id)
    }
  }
}
</script>